<?php
/**
 * 趣享全国运营商发送新版本
 * @author zhiyong.luo
 */
class c2_task_model_v2 extends nn_public_model
{
    /**
     * 主媒资修改、添加
     * @param
     */
    public function do_video()
    {
        $action = ($this->arr_params['bk_c2_task_info']['nns_action'] != 'destroy') ? ($this->arr_params['bk_c2_task_info']['nns_action'] == 'update') ? 'UPDATE' : 'REGIST' : 'DELETE';
        if ($action == 'DELETE')
        {
            return $this->video_destroy();
        }

        if(!isset($this->arr_params['bk_c2_task_info']['nns_ref_id']) || empty($this->arr_params['bk_c2_task_info']['nns_ref_id']))
        {
            return $this->_make_return_data(1,'点播传入参数无nns_video_id字段,参数为:'.var_export($this->arr_params));
        }
        $video_id = $this->arr_params['bk_c2_task_info']['nns_ref_id'];
        include_once dirname(dirname(dirname(dirname(__FILE__)))).'/nn_logic/video/vod.class.php';
        include_once dirname(dirname(dirname(dirname(__FILE__)))).'/nn_logic/depot/depot.class.php';
        //查询主媒资信息
        $result_video = nl_vod::get_video_info_by_id($this->obj_dc, $video_id);
        if($result_video['ret'] != 0)
        {
            return $result_video;
        }
        if(!isset($result_video['data_info'][0]) || !is_array($result_video['data_info'][0]) || empty($result_video['data_info'][0]))
        {
            //主媒资已被删除
            //nl_execute_by_db("update nns_mgtvbk_c2_task  set nns_status=7,nns_action='destroy',nns_epg_status=100 where nns_id='{$this->arr_params['bk_c2_task_info']['nns_id']}'", $this->obj_dc->db());
            return $result_video;
        }
        $result_video = $result_video['data_info'][0];
        //主媒资扩展信息
        $result_video_ex = nl_vod::query_ex_by_id($this->obj_dc,$result_video['nns_asset_import_id'],$result_video['nns_cp_id']);
        $result_video_ex = array_column($result_video_ex['data_info'], 'nns_value', 'nns_key');
        //查询CP信息
//        $result_cp_config = nl_cp::query_by_id($this->obj_dc, $result_video['nns_cp_id']);
//        if($result_cp_config['ret'] != 0)
//        {
//            return $result_cp_config;
//        }
//        $this->arr_cp_config = (isset($result_cp_config['data_info']['nns_config']) && strlen($result_cp_config['data_info']['nns_config']) >0) ? json_decode($result_cp_config['data_info']['nns_config'],true) : null;
        //获取注入ID
        $result_video_import_info = public_model_exec::get_asset_id_by_sp_id($this->str_sp_id, 'video', $video_id,$result_video,$this->arr_sp_config);
        if($result_video_import_info['ret'] != 0 || !isset($result_video_import_info['data_info']) || strlen($result_video_import_info['data_info']) <1)
        {
            return $result_video_import_info;
        }
        $cdn_import_id = $result_video_import_info['data_info'];
        //获取资源库栏目
        $result_depot = nl_depot::get_depot_info($this->obj_dc, null,'video');
        if($result_depot['ret'] !=0)
        {
            return $result_depot;
        }
        $category_name = (isset($result_video['nns_all_index']) && (int)$result_video['nns_all_index'] >1) ? '电视剧' : '电影';

        if(isset($result_depot['data_info'][0]['nns_category']) && strlen($result_depot['data_info'][0]['nns_category']) > 0)
        {
            $dom = new DOMDocument('1.0', 'utf-8');
            $dom->loadXML($result_depot['data_info'][0]['nns_category']);
            $categorys = $dom->getElementsByTagName('category');
            foreach ($categorys as $category)
            {
                $nns_cdn_category_id = (string)$category->getAttribute('id');
                if($nns_cdn_category_id == $result_video['nns_category_id'])
                {
                    $category_name = $category->getAttribute('name');
                    break;
                }
            }
        }

        $task_type = 'Series';
        //组装XML数组
        $arr_xml = array(
            'Objects' => array(
                array(
                    'ID' => $cdn_import_id,
                    'Action' => $action,
                    'Code' => $cdn_import_id,
                    'ElementType' => $task_type,
                    'Property' => array(
                        'Name' => $result_video['nns_name'],//节目名称
                        'AliasName' => $result_video['nns_alias_name'],//节目别名
                        'EnglishName' => $result_video['nns_eng_name'],//节目英文名称
                        'Compere' => '',//群众演员，多个以/分隔
                        'WriterDisplay' => $result_video['nns_director'],//导演，多个以/分隔
                        'ActorDisplay' => $result_video['nns_actor'],//演员，多个以/分隔
                        'Type' => $category_name, //节目类型，如电影、电视剧等
                        'ViewType' => $result_video['nns_view_type'],//节目类型对应标识
                        'Kind' => $result_video['nns_kind'],//影片类型标签，如动作、爱情等，多个以/分隔
                        'KeyWords' => $result_video['nns_keyword'],//影片关键字，如年代等，多个以/分隔
                        'OriginalCountry' => $result_video['nns_area'],//节目出产地
                        'ReleaseYear' => $result_video['nns_show_time'],//上映日期
                        'VolumnCount' => $result_video['nns_all_index'],
                        'Description' => $result_video['nns_summary'],
                        'ContentProvider' => $result_video['nns_cp_id'],
                        'Duration' => $result_video['nns_view_len'],
                        'Language' => $result_video['nns_language'],
                        'PlayCount' => '',
                        'Copyright' => '',
                        'LicensingWindowStart' => $result_video['nns_copyright_begin_date'],
                        'LicensingWindowEnd' => $result_video['nns_copyright_range'],
                        'ParentCategoryId' => '',
                        'ParentCategoryName' => '',
                        'OnlineIdentify' => '',
                    ),
                ),
            ),
        );
        //主媒资海报处理
        if(!empty($result_video['nns_image2'])) //小图
        {
            $img_s_id = np_guid_rand();
            $arr_xml['Objects'][] = array(
                'ID' => $img_s_id,
                'Action' => $action,
                'Code' => $img_s_id,
                'ElementType' => 'Picture',
                'Property' => array(
                    'FileURL' => $result_video['nns_image2'],//下载地址
                    'Type' => 2,//小图
                ),
            );
            $arr_xml['Mappings'][] = array(
                'ParentType' => 'Picture',
                'ParentID' => $img_s_id,
                'ParentCode' => $img_s_id,
                'ElementType' => $task_type,
                'ElementCode' => $cdn_import_id,
                'ElementID' => $cdn_import_id,
                'Action' => $action,
                'Property' => array(
                    'Type' => 2,//小图
                ),
            );
        }
        if(!empty($result_video['nns_image_v'])) //竖图
        {
            $img_v_id = np_guid_rand();
            $arr_xml['Objects'][] = array(
                'ID' => $img_v_id,
                'Action' => $action,
                'Code' => $img_v_id,
                'ElementType' => 'Picture',
                'Property' => array(
                    'FileURL' => $result_video['nns_image_v'],//下载地址
                    'Type' => 3,//小图
                ),
            );
            $arr_xml['Mappings'][] = array(
                'ParentType' => 'Picture',
                'ParentID' => $img_v_id,
                'ParentCode' => $img_v_id,
                'ElementType' => $task_type,
                'ElementCode' => $cdn_import_id,
                'ElementID' => $cdn_import_id,
                'Action' => $action,
                'Property' => array(
                    'Type' => 3,//小图
                ),
            );
        }
        if(!empty($result_video['nns_image_h'])) //横图
        {
            $img_h_id = np_guid_rand();
            $arr_xml['Objects'][] = array(
                'ID' => $img_h_id,
                'Action' => $action,
                'Code' => $img_h_id,
                'ElementType' => 'Picture',
                'Property' => array(
                    'FileURL' => $result_video['nns_image_h'],//下载地址
                    'Type' => 4,//横图
                ),
            );
            $arr_xml['Mappings'][] = array(
                'ParentType' => 'Picture',
                'ParentID' => $img_h_id,
                'ParentCode' => $img_h_id,
                'ElementType' => $task_type,
                'ElementCode' => $cdn_import_id,
                'ElementID' => $cdn_import_id,
                'Action' => $action,
                'Property' => array(
                    'Type' => 4,//横图
                ),
            );
        }
        if(!empty($result_video['nns_image_s'])) //方图
        {
            $img_id = np_guid_rand();
            $arr_xml['Objects'][] = array(
                'ID' => $img_id,
                'Action' => $action,
                'Code' => $img_id,
                'ElementType' => 'Picture',
                'Property' => array(
                    'FileURL' => $result_video['nns_image_s'],//下载地址
                    'Type' => 5,//方图
                ),
            );
            $arr_xml['Mappings'][] = array(
                'ParentType' => 'Picture',
                'ParentID' => $img_id,
                'ParentCode' => $img_id,
                'ElementType' => $task_type,
                'ElementCode' => $cdn_import_id,
                'ElementID' => $cdn_import_id,
                'Action' => $action,
                'Property' => array(
                    'Type' => 5,//方图
                ),
            );
        }
        $xml_str = $this->__array_make_to_xml($arr_xml);

        $str_guid = np_guid_rand();
        $file_name = $this->str_sp_id . '_' . date('His') . '_' . $str_guid . '_' . 'vod_video' . '_' . $action . '.xml';
        $c2_info = array(
            'nns_task_type' => $task_type,
            'nns_task_id' => isset($this->arr_params['bk_c2_task_info']['nns_id'])?$this->arr_params['bk_c2_task_info']['nns_id']:null,
            'nns_task_name'=> isset($this->arr_params['bk_c2_task_info']['nns_name'])?$this->arr_params['bk_c2_task_info']['nns_name']:null,
            'nns_action' =>	$action,
            'nns_url' => $file_name,
            'nns_content' => $xml_str,
            'nns_desc' => $task_type.','.$action,
            'nns_id' => $str_guid,
        );
        return $this->execute_self_bk_c2($c2_info);
    }

    /**
     * 主媒资删除
     * @return Ambigous|array|multitype
     */
    private function video_destroy()
    {
        $action = 'DELETE';
        $task_type = 'Series';
        if(!isset($this->arr_params['bk_c2_task_info']['nns_ref_id']) || empty($this->arr_params['bk_c2_task_info']['nns_ref_id']))
        {
            return $this->_make_return_data(1,'点播传入参数无nns_video_id字段,参数为:'.var_export($this->arr_params));
        }
        $video_id = $this->arr_params['bk_c2_task_info']['nns_ref_id'];
        include_once dirname(dirname(dirname(dirname(__FILE__)))).'/nn_logic/video/vod.class.php';
        //查询主媒资信息
        $result_video = nl_vod::get_video_info_by_id($this->obj_dc, $video_id);
        if($result_video['ret'] != 0)
        {
            return $result_video;
        }
        if(!isset($result_video['data_info'][0]) || !is_array($result_video['data_info'][0]) || empty($result_video['data_info'][0]))
        {
            //主媒资已被删除
            //nl_execute_by_db("update nns_mgtvbk_c2_task  set nns_status=7,nns_action='destroy',nns_epg_status=100 where nns_id='{$this->arr_params['bk_c2_task_info']['nns_id']}'", $this->obj_dc->db());
            return $result_video;
        }
        $result_video = $result_video['data_info'][0];
        //获取注入ID
        $result_video_import_info = public_model_exec::get_asset_id_by_sp_id($this->str_sp_id, 'video', $video_id,$result_video,$this->arr_sp_config);
        if($result_video_import_info['ret'] != 0 || !isset($result_video_import_info['data_info']) || strlen($result_video_import_info['data_info']) <1)
        {
            return $result_video_import_info;
        }
        $cdn_import_id = $result_video_import_info['data_info'];
        //组装XML数组
        $arr_xml = array(
            'Objects' => array(
                array(
                    'ID' => $cdn_import_id,
                    'Action' => $action,
                    'Code' => $cdn_import_id,
                    'ElementType' => $task_type,
                )
            )
        );
        $xml_str = $this->__array_make_to_xml($arr_xml);
        $str_guid = np_guid_rand();
        $file_name = $this->str_sp_id . '_' . date('His') . '_' . $str_guid . '_' . 'vod_video' . '_' . $action . '.xml';
        $c2_info = array(
            'nns_task_type' => $task_type,
            'nns_task_id' => isset($this->arr_params['bk_c2_task_info']['nns_id'])?$this->arr_params['bk_c2_task_info']['nns_id']:null,
            'nns_task_name'=> isset($this->arr_params['bk_c2_task_info']['nns_name'])?$this->arr_params['bk_c2_task_info']['nns_name']:null,
            'nns_action' =>	$action,
            'nns_url' => $file_name,
            'nns_content' => $xml_str,
            'nns_desc' => $task_type.','.$action,
            'nns_id' => $str_guid,
        );
        return $this->execute_self_bk_c2($c2_info);
    }

    /**
     * 分集添加、修改
     * @param
     */
    public function do_index()
    {
        $action = ($this->arr_params['bk_c2_task_info']['nns_action'] !='destroy') ? ($this->arr_params['bk_c2_task_info']['nns_action'] == 'update') ? 'UPDATE' : 'REGIST' : 'DELETE';
        if($action == 'DELETE')
        {
            return $this->index_destroy();
        }
        $task_type = 'Program';
        if(!isset($this->arr_params['bk_c2_task_info']['nns_ref_id']) || empty($this->arr_params['bk_c2_task_info']['nns_ref_id']))
        {
            return $this->_make_return_data(1,'点播传入参数无nns_index_id字段,参数为:'.var_export($this->arr_params));
        }
        $index_id = $this->arr_params['bk_c2_task_info']['nns_ref_id'];
        include_once dirname(dirname(dirname(dirname(__FILE__)))).'/nn_logic/video/vod_index.class.php';
        include_once dirname(dirname(dirname(dirname(__FILE__)))).'/nn_logic/video/vod.class.php';
        //查询分集信息
        $result_index = nl_vod_index::get_video_index_info_by_id($this->obj_dc, $index_id);
        if($result_index['ret'] != 0)
        {
            return $result_index;
        }
        if(!isset($result_index['data_info'][0]) || !is_array($result_index['data_info'][0]) || empty($result_index['data_info'][0]))
        {
            //分集不存在
            //nl_execute_by_db("update nns_mgtvbk_c2_task  set nns_status=7,nns_action='destroy',nns_epg_status=100 where nns_id='{$this->arr_params['bk_c2_task_info']['nns_id']}'", $this->obj_dc->db());
            return $result_index;
        }
        $result_index = $result_index['data_info'][0];
        //获取分集注入ID
        $result_index_import_info = public_model_exec::get_asset_id_by_sp_id($this->str_sp_id, 'index', $index_id,$result_index,$this->arr_sp_config);
        if($result_index_import_info['ret'] !=0 || !isset($result_index_import_info['data_info']) || strlen($result_index_import_info['data_info']) <1)
        {
            return $result_index_import_info;
        }
        $cdn_import_id = $result_index_import_info['data_info'];

        //分集扩展信息
//        $result_index_ex = nl_vod_index::query_ex_by_id($this->obj_dc,$result_index['nns_import_id'],$result_index['nns_cp_id']);
//        $result_index_ex = array_column($result_index_ex['data_info'], 'nns_value', 'nns_key');

        //主媒资信息
        $result_video = nl_vod::get_video_info_by_id($this->obj_dc, $result_index['nns_vod_id']);
        if($result_video['ret'] !=0)
        {
            return $result_video;
        }
        if(!isset($result_video['data_info'][0]) || !is_array($result_video['data_info'][0]) || empty($result_video['data_info'][0]))
        {
            //nl_execute_by_db("update nns_mgtvbk_c2_task  set nns_status=7,nns_action='destroy',nns_epg_status=100 where nns_id='{$this->arr_params['bk_c2_task_info']['nns_id']}'", $this->obj_dc->db());
            return $result_video;
        }
        $result_video = $result_video['data_info'][0];
        //获取CP信息
//        $result_cp_config = nl_cp::query_by_id($this->obj_dc, $result_video['nns_cp_id']);
//        if($result_cp_config['ret'] !=0)
//        {
//            return $result_cp_config;
//        }
//        $this->arr_cp_config = (isset($result_cp_config['data_info']['nns_config']) && strlen($result_cp_config['data_info']['nns_config']) >0) ? json_decode($result_cp_config['data_info']['nns_config'],true) : null;
        //获取主媒资注入ID
        $result_video_import_info = public_model_exec::get_asset_id_by_sp_id($this->str_sp_id, 'video', $result_index['nns_vod_id'],$result_video,$this->arr_sp_config);
        if($result_video_import_info['ret'] != 0 || !isset($result_video_import_info['data_info']) || strlen($result_video_import_info['data_info']) < 1)
        {
            return $result_video_import_info;
        }
        $cdn_video_import_id = $result_video_import_info['data_info'];

        //组装XML数组
        $arr_xml = array(
            'Objects' => array(
                array(
                    'ID' => $cdn_import_id,
                    'Action' => $action,
                    'Code' => $cdn_import_id,
                    'ElementType' => $task_type,
                    'Property' => array(
                        'Name' => $result_index['nns_name'],//节目名称
                        'OriginalName' => '',//别名
                        'WatchFocus' => $result_index['nns_watch_focus'],//分集看点
                        'WriterDisplay' => $result_index['nns_director'],//导演，多个以/分隔
                        'ActorDisplay' => $result_index['nns_actor'],//演员，多个以/分隔个以/分隔
                        'KeyWords' => '',//影片关键字，如年代等，多个以/分隔
                        'OriginalCountry' => '',//节目出产地
                        'ReleaseYear' => $result_index['nns_release_time'],//上映日期
                        'Description' => $result_index['nns_summary'],
                        'Duration' => $result_index['nns_time_len'],//节目单集时长，电影单集系列可录入，以秒为单位
                        'Language' => '',//语言
                    ),
                ),
            ),
            'Mappings' => array(
                array(
                    'ParentType' => 'Series',
                    'ParentID' => $cdn_video_import_id,
                    'ParentCode' => $cdn_video_import_id,
                    'ElementType' => $task_type,
                    'ElementCode' => $cdn_import_id,
                    'ElementID' => $cdn_import_id,
                    'Action' => $action,
                    'Property' => array(
                        'Sequence' => $result_index['nns_index'],//标识Program分集数，以0开始
                    )
                )
            ),
        );
        //分集海报不要
        $xml_str = $this->__array_make_to_xml($arr_xml);
        $str_guid = np_guid_rand();
        $file_name = $this->str_sp_id . '_' . date('His') . '_' . $str_guid . '_' . 'vod_index' . '_' . $action . '.xml';
        $c2_info = array(
            'nns_task_type'=>'Program',
            'nns_task_id'=> isset($this->arr_params['bk_c2_task_info']['nns_id'])?$this->arr_params['bk_c2_task_info']['nns_id']:null,
            'nns_task_name'=> isset($this->arr_params['bk_c2_task_info']['nns_name'])?$this->arr_params['bk_c2_task_info']['nns_name']:null,
            'nns_action'=>	$action,
            'nns_url' => $file_name,
            'nns_content' => $xml_str,
            'nns_desc' => $task_type.','.$action,
            'nns_id' => $str_guid,
        );
        return $this->execute_self_bk_c2($c2_info);
    }

    /**
     * 分集删除
     * @return mixed
     */
    private function index_destroy()
    {
        $task_type = "Program";
        $action = 'DELETE';
        if(!isset($this->arr_params['bk_c2_task_info']['nns_ref_id']) || empty($this->arr_params['bk_c2_task_info']['nns_ref_id']))
        {
            return $this->_make_return_data(1,'点播传入参数无nns_index_id字段,参数为:'.var_export($this->arr_params));
        }
        $index_id = $this->arr_params['bk_c2_task_info']['nns_ref_id'];
        include_once dirname(dirname(dirname(dirname(__FILE__)))).'/nn_logic/video/vod_index.class.php';
        //查询分集信息
        $result_index = nl_vod_index::get_video_index_info_by_id($this->obj_dc, $index_id);
        if($result_index['ret'] != 0)
        {
            return $result_index;
        }
        if(!isset($result_index['data_info'][0]) || !is_array($result_index['data_info'][0]) || empty($result_index['data_info'][0]))
        {
            //分集不存在
            //nl_execute_by_db("update nns_mgtvbk_c2_task  set nns_status=7,nns_action='destroy',nns_epg_status=100 where nns_id='{$this->arr_params['bk_c2_task_info']['nns_id']}'", $this->obj_dc->db());
            return $result_index;
        }
        $result_index = $result_index['data_info'][0];
        //获取分集注入ID
        $result_index_import_info = public_model_exec::get_asset_id_by_sp_id($this->str_sp_id, 'index', $index_id,$result_index,$this->arr_sp_config);
        if($result_index_import_info['ret'] != 0 || !isset($result_index_import_info['data_info']) || strlen($result_index_import_info['data_info']) < 1)
        {
            return $result_index_import_info;
        }
        $cdn_import_id = $result_index_import_info['data_info'];

        //组装XML数组
        $arr_xml = array(
            'Objects' => array(
                array(
                    'ID' => $cdn_import_id,
                    'Action' => $action,
                    'Code' => $cdn_import_id,
                    'ElementType' => $task_type,
                )
            )
        );
        $xml_str = $this->__array_make_to_xml($arr_xml);
        $str_guid = np_guid_rand();
        $file_name = $this->str_sp_id . '_' . date('His') . '_' . $str_guid . '_' . 'vod_video' . '_' . $action . '.xml';
        $c2_info = array(
            'nns_task_type' => $task_type,
            'nns_task_id' => isset($this->arr_params['bk_c2_task_info']['nns_id'])?$this->arr_params['bk_c2_task_info']['nns_id']:null,
            'nns_task_name'=> isset($this->arr_params['bk_c2_task_info']['nns_name'])?$this->arr_params['bk_c2_task_info']['nns_name']:null,
            'nns_action' =>	$action,
            'nns_url' => $file_name,
            'nns_content' => $xml_str,
            'nns_desc' => $task_type.','.$action,
            'nns_id' => $str_guid,
        );
        return $this->execute_self_bk_c2($c2_info);
    }
    /**
     * 片源添加
     * @param
     */
    public function do_media()
    {
        $action = ($this->arr_params['bk_c2_task_info']['nns_action'] !='destroy') ? ($this->arr_params['bk_c2_task_info']['nns_action'] == 'update') ? 'UPDATE' : 'REGIST' : 'DELETE';
        if($action == 'DELETE')
        {
            return $this->media_destroy();
        }
        $task_type = 'Movie';
        if(!isset($this->arr_params['nns_media_id']) || empty($this->arr_params['nns_media_id']))
        {
            return $this->_make_return_data(1,'点播传入参数无nns_media_id字段,参数为:'.var_export($this->arr_params));
        }
        $movie_id = $this->arr_params['nns_media_id'];
        include_once dirname(dirname(dirname(dirname(__FILE__)))).'/nn_logic/vod_media/vod_media.class.php';
        include_once dirname(dirname(dirname(dirname(__FILE__)))).'/nn_logic/video/vod_index.class.php';
        include_once dirname(dirname(dirname(dirname(__FILE__)))).'/nn_logic/video/vod.class.php';
        //片源信息
        $result_media = nl_vod_media_v2::query_by_id($this->obj_dc, $movie_id);
        if($result_media['ret'] != 0)
        {
            return $result_media;
        }
        if(!isset($result_media['data_info']) || !is_array($result_media['data_info']) || empty($result_media['data_info']))
        {
            //片源不存在
            //nl_execute_by_db("update nns_mgtvbk_c2_task  set nns_status=7,nns_action='destroy',nns_epg_status=100 where nns_id='{$this->arr_params['nns_task_id']}'", $this->obj_dc->db());
            return $result_media;
        }
        $result_media = $result_media['data_info'];
        //获取注入ID
        $result_media_import_info = public_model_exec::get_asset_id_by_sp_id($this->str_sp_id, 'media', $movie_id,$result_media,$this->arr_sp_config);
        if($result_media_import_info['ret'] != 0 || !isset($result_media_import_info['data_info']) || strlen($result_media_import_info['data_info']) <1)
        {
            return $result_media_import_info;
        }
        $cdn_import_id = $result_media_import_info['data_info'];
        //片源扩展信息
//        $result_media_ex = nl_vod_media_v2::query_ex_by_id($this->obj_dc, $result_media['nns_import_id'],$result_media['nns_cp_id']);
//        $result_media_ex = array_column($result_media_ex['data_info'], 'nns_value', 'nns_key');
        //分集信息
        $result_index = nl_vod_index::get_video_index_info_by_id($this->obj_dc, $result_media['nns_vod_index_id']);
        if($result_index['ret'] !=0)
        {
            return $result_index;
        }
        if(!isset($result_index['data_info'][0]) || !is_array($result_index['data_info'][0]) || empty($result_index['data_info'][0]))
        {
            //nl_execute_by_db("update nns_mgtvbk_c2_task  set nns_status=7,nns_action='destroy',nns_epg_status=100 where nns_id='{$this->arr_params['nns_task_id']}'", $this->obj_dc->db());
            return $result_index;
        }
        $result_index = $result_index['data_info'][0];
        //获取分集注入ID
        $result_index_import_info = public_model_exec::get_asset_id_by_sp_id($this->str_sp_id, 'index', $result_media['nns_vod_index_id'],$result_index,$this->arr_sp_config);
        if($result_index_import_info['ret'] != 0 || !isset($result_index_import_info['data_info']) || strlen($result_index_import_info['data_info']) <1)
        {
            return $result_index_import_info;
        }
        $cdn_index_import_id = $result_index_import_info['data_info'];

//        $result_cp_config = nl_cp::query_by_id($this->obj_dc, $result_video['nns_cp_id']);
//        if($result_cp_config['ret'] !=0)
//        {
//            return $result_cp_config;
//        }
//        $this->arr_cp_config = (isset($result_cp_config['data_info']['nns_config']) && strlen($result_cp_config['data_info']['nns_config']) >0) ? json_decode($result_cp_config['data_info']['nns_config'],true) : null;
        switch (strtoupper($result_media['nns_mode']))
        {
            case 'LOW':
                $media_mode = 1;
                break;
            case 'STD':
                $media_mode = 2;
                break;
            case 'HD':
                $media_mode = 3;
                break;
            case 'SD':
                $media_mode = 4;
                break;
            case '4K':
                $media_mode = 5;
                break;
            default:
                $media_mode = 3;
                break;
        }
        //组装XML数组
        $arr_xml = array(
            'Objects' => array(
                array(
                    'ID' => $cdn_import_id,
                    'Action' => $action,
                    'Code' => $cdn_import_id,
                    'ElementType' => $task_type,
                    'Property' => array(
                        'Name' => $result_media['nns_name'],//片源名称
                        'Duration' => $result_media['nns_file_time_len'],//节目时长
                        'SystemLayer' => 1,//文件格式  默认为1，1 TS，2 3GP，3 flv，4 MP4，5 wmv，6 mp3
                        'Type' => 1,//媒体类型默认为1，1 正片，2 花絮/短，3 预告片，4 回看点播源
                        'FileURL' => !empty($this->arr_params['bk_c2_task_info']['nns_file_path']) ? $this->arr_params['bk_c2_task_info']['nns_file_path'] : $result_media['nns_url'],//下载地址
                        'MediaMode' => $media_mode,//清晰度
                        'Resolution' => $result_media['nns_file_resolution'],//分辨率
                        'FileSize' => !empty($this->arr_params['bk_c2_task_info']['nns_file_size']) ? $this->arr_params['bk_c2_task_info']['nns_file_size'] : $result_media['nns_file_size'],
                        'BitRateType' => $result_media['nns_kbps'],
                        'Tag' => '',
                        'MediaType' => '',
                        'LiveId' => '',
                        'BeginTime' => '',
                    ),
                ),
            ),
            'Mappings' => array(
                array(
                    'ParentType' => 'Program',
                    'ParentID' => $cdn_index_import_id,
                    'ParentCode' => $cdn_index_import_id,
                    'ElementType' => $task_type,
                    'ElementCode' => $cdn_import_id,
                    'ElementID' => $cdn_import_id,
                    'Action' => $action,
                )
            ),
        );
        $xml_str = $this->__array_make_to_xml($arr_xml);

        $str_guid = np_guid_rand();
        $file_name = $this->str_sp_id . '_' . date('His') . '_' . $str_guid . '_' . 'vod_media' . '_' . $action . '.xml';
        $c2_info = array(
            'nns_task_type'=>$task_type,
            'nns_task_id'=> isset($this->arr_params['nns_task_id'])?$this->arr_params['nns_task_id']:null,
            'nns_task_name'=> isset($this->arr_params['nns_task_name'])?$this->arr_params['nns_task_name']:null,
            'nns_action'=>	$action,
            'nns_url' => $file_name,
            'nns_content' => $xml_str,
            'nns_desc' => $task_type.','.$action,
            'nns_id'=>$str_guid,
        );
        return $this->execute_self_bk_c2($c2_info);
    }

    /**
     * 片源删除
     * @return Ambigous|array|multitype
     */
    private function media_destroy()
    {
        $task_type = "Movie";
        $action = 'DELETE';

        if(!isset($this->arr_params['nns_media_id']) || empty($this->arr_params['nns_media_id']))
        {
            return $this->_make_return_data(1,'点播传入参数无nns_media_id字段,参数为:'.var_export($this->arr_params));
        }
        $movie_id = $this->arr_params['nns_media_id'];
        include_once dirname(dirname(dirname(dirname(__FILE__)))).'/nn_logic/vod_media/vod_media.class.php';
        include_once dirname(dirname(dirname(dirname(__FILE__)))).'/nn_logic/video/vod_index.class.php';
        include_once dirname(dirname(dirname(dirname(__FILE__)))).'/nn_logic/video/vod.class.php';
        //片源信息
        $result_media = nl_vod_media_v2::query_by_id($this->obj_dc, $movie_id);
        if($result_media['ret'] != 0)
        {
            return $result_media;
        }
        if(!isset($result_media['data_info']) || !is_array($result_media['data_info']) || empty($result_media['data_info']))
        {
            //片源不存在
            //nl_execute_by_db("update nns_mgtvbk_c2_task  set nns_status=7,nns_action='destroy',nns_epg_status=100 where nns_id='{$this->arr_params['nns_task_id']}'", $this->obj_dc->db());
            return $result_media;
        }
        $result_media = $result_media['data_info'];
        //获取注入ID
        $result_media_import_info = public_model_exec::get_asset_id_by_sp_id($this->str_sp_id, 'media', $movie_id,$result_media,$this->arr_sp_config);
        if($result_media_import_info['ret'] != 0 || !isset($result_media_import_info['data_info']) || strlen($result_media_import_info['data_info']) <1)
        {
            return $result_media_import_info;
        }
        $cdn_import_id = $result_media_import_info['data_info'];
        //组装XML数组
        $arr_xml = array(
            'Objects' => array(
                array(
                    'ID' => $cdn_import_id,
                    'Action' => $action,
                    'Code' => $cdn_import_id,
                    'ElementType' => $task_type,
                )
            )
        );
        $xml_str = $this->__array_make_to_xml($arr_xml);

        $str_guid = np_guid_rand();
        $file_name = $this->str_sp_id . '_' . date('His') . '_' . $str_guid . '_' . 'vod_media' . '_' . $action . '.xml';
        $c2_info = array(
            'nns_task_type'=>$task_type,
            'nns_task_id'=> isset($this->arr_params['nns_task_id'])?$this->arr_params['nns_task_id']:null,
            'nns_task_name'=> isset($this->arr_params['nns_task_name'])?$this->arr_params['nns_task_name']:null,
            'nns_action'=>	$action,
            'nns_url' => $file_name,
            'nns_content' => $xml_str,
            'nns_desc' => $task_type.','.$action,
            'nns_id'=>$str_guid,
        );
        return $this->execute_self_bk_c2($c2_info);
    }
    /**
     * @param unknown $c2_info
     */
    public function execute_self_bk_c2($c2_info)
    {
        $c2_info['nns_type'] = 'std';
        $c2_info['nns_org_id'] = $this->str_sp_id;
        $c2_info['nns_id'] = np_guid_rand();
        $sub_path = date('Y-m-d');
        $file = $c2_info['nns_url'];
        $c2_info['nns_url'] = $sub_path . '/' . $file;
        //生成soap xml文件 路径
        $file_path = dirname(dirname(dirname(dirname(__FILE__)))) . '/data/mgtv/' . $this->str_sp_id . '/inject_xml/' . $sub_path . '/';
        if (!is_dir($file_path))
        {
            @mkdir($file_path, 0777, true);
        }
        $file_path .= $file;
        @file_put_contents($file_path, $c2_info['nns_content']);
        //HTTP发送
        $import_bool = true;
        if((int)$this->arr_sp_config["cdn_send_mode"] === 1) //HTTP+POST注入
        {
            include_once dirname(dirname(dirname(dirname(dirname(__FILE__))))) . '/np/np_http_curl.class.php';
            $obj_curl = new np_http_curl_class();
            $data = array(
                'msgid' => $c2_info['nns_id'],
                'cpid' => $this->arr_sp_config['import_csp_id'],
                'xml' => $c2_info['nns_content']
            );
            $c2_info['nns_send_time'] = date("Y-m-d H:i:s",time());
            $result = $obj_curl->post($this->arr_sp_config['cdn_send_mode_url'],$data);
            $c2_info['nns_notify_time'] = date("Y-m-d H:i:s",time());
            $curl_info = $obj_curl->curl_getinfo();

            //发送CDN时，发生的异常处理【理解为发送状态】
            if($curl_info['http_code'] != '200')
            {
                $c2_info['nns_result'] = "[-1]";
                $c2_info['nns_notify_result'] = -1;
                $c2_info['nns_notify_fail_reason'] = '发送失败';
                $import_bool = false;
            }
            else
            {
                $c2_info['nns_result'] = "[0]";
                $simp_arr = simplexml_load_string($result);
                $re_arr = json_decode(json_encode($simp_arr),true);
                if($re_arr['@attributes']['ret'] != 0)
                {
                    $c2_info['nns_notify_result'] = $re_arr['@attributes']['ret'];
                    $c2_info['nns_notify_fail_reason'] = $re_arr['@attributes']['reason'];
                    $import_bool = false;
                }
                else
                {
                    $c2_info['nns_notify_result'] = $re_arr['@attributes']['ret'];
                    $c2_info['nns_notify_fail_reason'] = '成功';
                    //修改C2任务为成功状态
                    nl_execute_by_db("update nns_mgtvbk_c2_task set nns_status=0,nns_modify_time=now() where nns_id='{$c2_info['nns_task_id']}'",$this->obj_dc->db());
                }
            }
        }
        elseif ((int)$this->arr_sp_config["cdn_send_mode"] === 2) //FTP 注入
        {
            //FTP模式。上传到指定的FTP服务器上
            $up_re = $this->up_to_ftp($file_path,$this->arr_sp_config['ftp_cdn_send_mode_url'],false);
            if($up_re['ret'] != 0)
            {
                //删除本地文件
                unlink($file_path);
                $c2_info['nns_result'] = "[-1]";
                $c2_info['nns_notify_result'] = -1;
                $c2_info['nns_notify_fail_reason'] = 'ADI文件上传至FTP失败:'.$up_re['reason'];
                $import_bool = false;
            }
            else
            {
                $c2_info['nns_notify_result'] = 0;
                $c2_info['nns_result'] = '[0]';
                $c2_info['nns_notify_fail_reason'] = '成功';
            }
        }
        nl_c2_log::add($this->obj_dc, $c2_info);

        if($import_bool)
        {
            return $this->_make_return_data(0,$c2_info['nns_notify_fail_reason']);
        }
        else
        {
            return $this->_make_return_data(1,$c2_info['nns_notify_fail_reason']);
        }
    }
    /**
     * XML生成
     * @param
     * $arr_data = array(
     *  'Objects' => array(
     *       array(
     *           'ID' => 'SERI2017091205971064',
     *           'Action' => 'REGIST',
     *           'Code' => 'SERI2017091205971064',
     *           'ElementType' => 'Series',
     *           'Property' => array(
     *               'Name' => 'XXXX',
     *               'AliasName' => 'VOD00000001',
     *           ),
     *       ),
     *       array(
     *           'ID' => 'PIC2017091205971064',
     *           'Action' => 'REGIST',
     *           'Code' => 'PIC2017091205971064',
     *           'ElementType' => 'Picture',
     *           'Property' => array(
     *               'FileURL' => 'http://127.0.0.1',
     *               'Type' => '4',
     *           ),
     *       ),
     *   ),
     *   'Mappings' => array(
     *       array(
     *               'ParentType' => "Picture",
     *               'ParentID'=>"PIC2017091205971064",
     *               'ParentCode'=>"PIC2017091205971064",
     *               'ElementType' => 'Series',
     *               'ElementID'=>"SERI2017091205971064",
     *               'ElementCode'=>"SERI2017091205971064",
     *               'Action'=>"REGIST",
     *           ),
     *       )
     * )
     */
    private function __array_make_to_xml($arr_data)
    {
        $obj_dom = new DOMDocument("1.0", 'utf-8');
        $adi = $obj_dom->createElement("ADI"); //创建ADI
        $adi_attr = $obj_dom->appendChild($adi);
        foreach ($arr_data as $k => $v)
        {
            $objects = $obj_dom->createElement($k);//创建Objects或者Mappings
            $objects_attr = $adi_attr->appendChild($objects);
            if(is_array($v) && !empty($v))
            {
                foreach ($v as $object_key => $object_value)
                {
                    $o_key = substr($k,0,-1);//创建Object或者Mapping
                    $object = $obj_dom->createElement($o_key);
                    $object_attr = $objects_attr->appendChild($object);
                    if(is_array($object_value) && !empty($object_value))//创建Object或者Mapping 节点值 Property
                    {
                        foreach ($object_value as $ob_key => $ob_val)
                        {
                            if($ob_key === 'Property' && !empty($ob_val) && is_array($ob_val))
                            {
                                foreach ($ob_val as $key => $value)
                                {
                                    $Property = $obj_dom->createElement('Property');
                                    $attr_key = $object_attr->appendChild($Property);
                                    $Property->setAttribute('Name',$key);
                                    $content = $obj_dom->createTextNode($value);
                                    $attr_key->appendchild($content);
                                }
                            }
                            else
                            {
                                $object->setAttribute($ob_key,$ob_val);
                            }
                        }
                    }
                    else
                    {
                        $object->setAttribute($object_key,$object_value);//创建Object或者Mapping 属性
                    }
                }
            }
        }

        return $obj_dom->saveXML();
    }
    /**
     * 把ADIxml文件上传至与FTP上
     * @param string $local_path 本地文件路径
     * @param string $up_ftp  上传FTP
     * @param bool $passive 主被动模式，默认被动模式
     * @return Ambigous <multitype:number , multitype:number string >
     */
    public function up_to_ftp($local_path,$up_ftp,$passive = true)
    {
        $arr_ftp = parse_url($up_ftp);
        if(!isset($arr_ftp['port']))
        {
            $arr_ftp['port'] = 21;
        }
        $ftp = new nns_ftp($arr_ftp['host'], $arr_ftp['user'], $arr_ftp['pass'], $arr_ftp['port']);
        $ftpcon = $ftp->connect(20, $passive);
        if(!$ftpcon)
        {
            return $this->_make_return_data(1,'FTP链接失败' . $up_ftp);
        }
        $path_arr = pathinfo($local_path);
        $path = empty($arr_ftp['path']) ? "./" : "." . $arr_ftp['path'];
        $ftp_re = $ftp->up($path, $path_arr['basename'], $local_path);
        if(!$ftp_re)
        {
            nn_log::write_log_message(LOG_MODEL_BK_CDN_SEND, "上传失败：".var_export($ftp->error(),true), $this->str_sp_id);
            $error_msg = '上传FTP'.$up_ftp.'失败,上传路径:'.$arr_ftp['path'].',上传文件名:'.$path_arr['basename'].',上传的本地文件:'.$local_path;
            return $this->_make_return_data(1,$error_msg);
        }
        return $this->_make_return_data(0,"上传成功");
    }
}